<?php
include("include/conn.php");

if(isset($_GET['bhatthiId']))
{
	$selectBhatthi = "SELECT bhatthibook.bhatthiDate, bhatthibookdetail.particulars, bhatthibookdetail.fine, bhatthibookdetail.amount,
                           bhatthibookdetail.CrDr, bhatthiparty.bhatthipartyName
                      FROM bhatthibookdetail
                      JOIN bhatthibook ON bhatthibook.bhatthiBookId = bhatthibookdetail.bhatthiBookId
                      JOIN bhatthiparty ON bhatthiparty.bhatthiPartyId = bhatthibook.bhatthiPartyId
                     WHERE bhatthibookdetail.bhatthiBookDetailId = ".$_GET['bhatthiId']."
                       AND bhatthibookdetail.inRojmel = 1";
  $selectBhatthiRes = mysql_query($selectBhatthi);
  if($row = mysql_fetch_assoc($selectBhatthiRes))
  {
  	$insertRojmel = "INSERT INTO rojmel (rojmelDate, particulars, fine, amount, CrDr)
  	                 VALUES ('".$row['bhatthiDate']."','".$row['particulars']." (".$row['bhatthipartyName'].")',".$row['fine'].",
  	                         ".$row['amount'].",'".$row['CrDr']."')";
    $insertRojmelRes = mysql_query($insertRojmel);
  }
	
  $bhatthiBook = "SELECT bhatthiBookId FROM bhatthibookdetail
                   WHERE bhatthiBookDetailId = ".$_GET['bhatthiId'];
  $bhatthiBookRes = mysql_query($bhatthiBook);
  if($bhatthiRow = mysql_fetch_assoc($bhatthiBookRes))
  {
    $selectBhatthiBook = "SELECT count(bhatthiBookId) AS counter FROM bhatthibookdetail
                           WHERE bhatthiBookId = ".$bhatthiRow['bhatthiBookId'];
    $selectBhatthiBookRes = mysql_query($selectBhatthiBook);
    if($dataRow = mysql_fetch_assoc($selectBhatthiBookRes))
    {
      if($dataRow['counter'] == 1)
      {
        $deleteBhatthiBook = "DELETE FROM bhatthibook
                               WHERE bhatthiBookId = ".$bhatthiRow['bhatthiBookId'];
        $deleteBhatthiBookRes = mysql_query($deleteBhatthiBook);
      }
    }
  }
  
  $bhatthiBookDetail = "DELETE FROM bhatthibookdetail
                         WHERE bhatthiBookDetailId = ".$_GET['bhatthiId'];
  $bhatthiBookDetailRes = mysql_query($bhatthiBookDetail);
  
  if(isset($_GET['rojmel']))
    header("location:rojmel.php");
  else
    header("location:bhatthiDetail.php");
}
else
   header("location:bhatthiDetail.php");
?>